<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
//	public function index() {
////		$this->display("user/index");
//	}

	//	public function login(){
	//		$this->display("login");
	//	}

	public function login() {
		if (IS_POST) {
			$username=$_POST["username"];
     		$password=$_POST["password"];
			$m = M('userinfo');
			$user = $m -> field('id,username,nickname') -> where("username= '" . $_POST['username'] . "' and password= '" . $_POST['password'] . "'") -> find();
			if ($user) {
				session_start();
				//查询用户的权限
				$_SESSION['id']=$user['id'];
				$_SESSION['username']=$user['username'];
				$user['code']=0;
				$user['rules']=$this -> getRuleByUserID($user['id']);
				$this -> ajaxReturn($user);
			} else {
				$obj = (object)array();
				$obj -> code = "104";
				$obj -> message = "用户名或密码不正确";
				$this -> ajaxReturn($obj);
			}

		} else if (IS_GET) {
			$this -> display();
		}
	}
//				if(IS_POST){
//					$obj=(object)array();
//					$obj->data=$_POST;
//					$m=M('userinfo');
//					$ret=$m->where("username='{$obj->data['username']}' and password='{$obj->data['password']}'")->select();
//					if($ret){
//						//开启会话
//						session_start();
//						$_SESSION["username"]=$obj->data['username'];
//						$_SESSION["id"]=$ret[0]['id'];
//						$obj->code=0;
//					    $obj->message="登录成功";
//						$this->ajaxReturn($obj);
//					}else{
//						$obj->code=1;
//						$obj->message="登录失败";
//						$this->ajaxReturn($obj);
//					}
//				}else{
//					$obj=(object)array();
//					$obj->code=1;
//					$obj->message="登录失败";
//					$this->display();
//				}
	

	private function getRuleByUserID($uid) {
		$access = M('auth_group_access');
		$group = $access -> field('rules') -> join('think_auth_group on think_auth_group.id=think_auth_group_access.group_id') -> where('uid=' . $uid) -> find();
		$rule = M('auth_rule');
		$userRules = $rule ->field('id,name,title,pid')-> where('id in (' .$group['rules'] . ') and is_menu=1') -> select();
		return $userRules;
	}



	
	
}
